package com.chapter1.basic.chain;

import java.util.Iterator;

/** 
 * @ClassName: MyChainStack 
 * @Description: 链表实现的栈
 * @author minjun minjun@bw30.com
 * @date 2015-2-12 上午10:37:13 
 *  
 */
public class MyChainStack<Item> implements Iterable<Item>{
	
	private Node first;
	
	private int index;

	/**
	 * 
	* @ClassName: Node 
	* @Description: 通过内部类来保护所有节点元素 
	* @author minjun minjun@bw30.com
	* @date 2015-2-12 上午10:58:54 
	*
	 */
	private class Node{
		
		Item item;
		
		Node next;
	}
	
	public void push(Item item){
		index++;
		Node oldFirst=first;
		//创建一个新的头结点
		first=new Node();
		first.item=item;
		first.next=oldFirst;
	}
	
	public Item pop(){
		if(!isEmpty()){
			index--;
			//将要移除的元素先保存下来，然后再移除他 
			Item item=first.item;
			first=first.next;
			return item;
		}
		return null;
	}
	
	public boolean isEmpty(){
		return index==0;
	}
	
	public int size(){
		return index;
	}
	
	@Override
	public Iterator<Item> iterator() {
		return new MyChainStackIterator();
	}
	
	private class MyChainStackIterator implements Iterator<Item>{
		
		/**
		 * 迭代器里面在单独将索引和链表头信息保存下来，以免破坏栈数据结构，无法二次迭代
		 */
		private int i=index;
		
		private Node f=first;

		@Override
		public boolean hasNext() {
			return i>0;
		}

		@Override
		public Item next() {
			if(i==0){
				throw new RuntimeException("没元素了");
			}
			i--;
			//将要移除的元素先保存下来，然后再移除他 
			Item item=f.item;
			f=f.next;
			return item;
		}

		@Override
		public void remove() {
			
		}
		
	}
	
}
